package com.sgb.kjwl.viewmodel.home;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sgb.kjwl.api.APIManager;
import com.sgb.jicai.entity.CentralizedMiningEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.sgb.kjwl.repository.HomeRepertory;
import com.swgk.core.mmkvutil.CacheMarker;
import com.sgb.kjwl.view.ui.fragment.home.CentralizedMiningItemFragment;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.mmkvutil.DatalUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CentralizedMiningItemModel extends BaseViewModel {

    private HomeRepertory repertory;
    private CentralizedMiningItemFragment fragment;

    public CentralizedMiningItemModel(CentralizedMiningItemFragment leaseFragment2, HomeRepertory repertory) {
        this.fragment = leaseFragment2;
        this.repertory = repertory;
    }



    /**
     * 首页只显示8条数据，无需传参
     */
    public void getJiCaiList(int groupbuyClass, boolean isRefresh) {
        boolean isShowDialog = true;
        if (groupbuyClass == 1) { // 商品材料数据缓存
            String json = MkvUtils.get().getString(MkvUtils.CacheModular, CacheMarker.CentralizedList, "");
            if (!TextUtils.isEmpty(json)) {
                isShowDialog = false;
                List<CentralizedMiningEntity> data = new Gson().fromJson(json, new TypeToken<List<CentralizedMiningEntity>>() {}.getType());
                fragment.showList(data);
            } else {
                isShowDialog = true;
            }
        }

        Map map = new HashMap();
        map.put("limit", 8);
        map.put("current", 1);
//        map.put("provinceNo", repertory.getAreaCode());
        map.put("groupbuyClass", groupbuyClass);
        if (isRefresh || isShowDialog) {
            DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        }
        APIManager.getInstance().getCentralizedMiningAPI().getJiCaiList(map).enqueue(new Callback<BaseEntity<ListResponse<List<CentralizedMiningEntity>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<ListResponse<List<CentralizedMiningEntity>>>> call, Response<BaseEntity<ListResponse<List<CentralizedMiningEntity>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    ArrayList<CentralizedMiningEntity> entities = new ArrayList<>();
                    for (CentralizedMiningEntity data : response.body().getData().getList()) {
                        // 集采状态（1 集采中 2 集采结束 4 集采失败 5 加盟中 6 报价中 ）
//                        if (data.getStatus() == 1 || data.getStatus() == 5 ||  data.getStatus() == 6) {
                        entities.add(data);
//                        }
                    }
                    if (groupbuyClass == 1) {// 商品材料数据缓存
                        Gson gson = new Gson();
                        //获取从网络请求下来的数据的哈希值
                        String dataJson = gson.toJson(entities);
                        String mHashNet = DatalUtils.strToHashKey(dataJson);
                        String hashData = DatalUtils.getHashData(MkvUtils.CacheModular, CacheMarker.CentralizedList);
                        if (!mHashNet.equals(hashData)) {
                            MkvUtils.get().putString(MkvUtils.CacheModular, CacheMarker.CentralizedList, dataJson);
                            fragment.showList(entities);
                        }
                    } else {
                        fragment.showList(entities);
                    }
                } else {
                    MToast.showToast(fragment.getContext(), response.body().getMsg());
                    fragment.showList(null);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<ListResponse<List<CentralizedMiningEntity>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
                fragment.showList(null);
            }
        });
    }


    public String getAreaCode() {
        if (TextUtils.isEmpty(repertory.getAreaCode()) || "0".equals(repertory.getAreaCode())){
            return "615000";
        }
        return repertory.getAreaCode();
    }

    public void getH5Url(String id) {
        DialogHelper.showProgressDialog(fragment.getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getUrlSetting("collection").enqueue(new Callback<BaseEntity<H5ReEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<H5ReEntity>> call, Response<BaseEntity<H5ReEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {//type 0 首页 1 我的集采 2 我的报价
                    SharedPreferenceUtil.init(fragment.getActivity());
                    String token = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.resourceAPPToken, "");
                    String url = response.body().getData().getUrl() + "?id=" + id + "&type=0" + "&token=" + repertory.getToken();
                    fragment.showUrl(url);
                } else {
                    MToast.showToast(fragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<H5ReEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }
}
